package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.draw.clip
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.sinogrand.elevator.ui.theme.AppConstants
import com.sinogrand.elevator.data.models.HomeElevatorItem
import com.sinogrand.elevator.repository.HomeRepository
import com.sinogrand.elevator.network.NetworkClient
import com.sinogrand.elevator.utils.LogTags
import com.google.gson.JsonObject
import androidx.compose.runtime.LaunchedEffect
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import android.util.Log

// 数据模型
@Parcelize
data class ElevatorItem(
    val id: String,
    val title: String,
    val description: String,
    val isExpired: Boolean,
    val expireDate: String,
    val imageUrl: String? = null
) : Parcelable

@Parcelize
data class ApprovalItem(
    val id: String,
    val title: String,
    val time: String,
    val formId: Int
) : Parcelable

@Parcelize
data class TodoItem(
    val id: String,
    val title: String,
    val time: String,
    val formId: Int
) : Parcelable

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    onNavigateToElevatorList: () -> Unit = {},
    onNavigateToElevatorDetail: (ElevatorItem) -> Unit = {},
    onNavigateToApproval: (Int) -> Unit = {}
) {
    val context = LocalContext.current
    
    // 使用 rememberSaveable 保持所有状态，确保页面切换时状态不丢失
    var homeElevatorList by rememberSaveable { mutableStateOf<List<HomeElevatorItem>>(emptyList()) }
    var isLoading by rememberSaveable { mutableStateOf(true) }
    var isRefreshing by rememberSaveable { mutableStateOf(false) }
    var isLoadingApproval by rememberSaveable { mutableStateOf(true) }
    var isLoadingTodo by rememberSaveable { mutableStateOf(true) }
    var approvalData by rememberSaveable { mutableStateOf<List<ApprovalItem>>(emptyList()) }
    var todoData by rememberSaveable { mutableStateOf<List<TodoItem>>(emptyList()) }
    
    // 使用 rememberSaveable 保持滚动状态
    val listState = rememberSaveable(saver = LazyListState.Saver) {
        LazyListState()
    }
    
    val homeRepository = remember { HomeRepository(context) }
    val apiService = remember { NetworkClient.getApiService(context) }
    
    // 将API数据转换为UI数据
    val displayElevatorData = homeElevatorList.map { homeItem ->
        val isExpired = isDateExpired(homeItem.end_date)
        ElevatorItem(
            id = homeItem.id.toString(),
            title = homeItem.name,
            description = "到期时间: ${homeItem.end_date}",
            isExpired = isExpired,
            expireDate = homeItem.end_date,
            imageUrl = null
        )
    }
    
    // 只在首次加载时执行数据加载
    LaunchedEffect(Unit) {
        // 如果数据为空，才进行加载
        if (homeElevatorList.isEmpty()) {
            try {
                val result = homeRepository.getHomeElevatorList(page = 1, size = 10)
                result.fold(
                    onSuccess = { response ->
                        homeElevatorList = response.list
                        isLoading = false
                    },
                    onFailure = { _ ->
                        homeElevatorList = emptyList()
                        isLoading = false
                    }
                )
            } catch (e: Exception) {
                homeElevatorList = emptyList()
                isLoading = false
            }
        } else {
            // 如果已有数据，直接设置为非加载状态
            isLoading = false
        }
    }
    
    // 加载待审批数据
    suspend fun loadApprovalData() {
        try {
            Log.d(LogTags.HOME_SCREEN, "开始加载待审批数据")
            isLoadingApproval = true
            
            val request = JsonObject().apply {
                addProperty("type", 1) // 1.待审批
            }
            
            val apiResponse = apiService.getTodoList(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                val todoItems = apiResponse.data.list
                Log.i(LogTags.HOME_SCREEN, "📋 获取到的待审批数据: ${todoItems.size}条")
                approvalData = todoItems.map { todoItem ->
                    Log.d(LogTags.HOME_SCREEN, "📄 待审批项目详情:")
                    Log.d(LogTags.HOME_SCREEN, "   🆔 id: ${todoItem.id}")
                    Log.d(LogTags.HOME_SCREEN, "   📝 title: ${todoItem.title}")
                    Log.d(LogTags.HOME_SCREEN, "   📅 created_at: ${todoItem.created_at}")
                    Log.d(LogTags.HOME_SCREEN, "   🔢 form_id: ${todoItem.form_id}")
                    ApprovalItem(
                        id = todoItem.id.toString(),
                        title = todoItem.title,
                        time = todoItem.created_at,
                        formId = todoItem.form_id
                    )
                }
                Log.i(LogTags.HOME_SCREEN, "✅ 成功加载待审批数据: ${approvalData.size}条")
            } else {
                Log.e(LogTags.HOME_SCREEN, "❌ 加载待审批数据失败: ${apiResponse.msg}")
                approvalData = emptyList()
            }
        } catch (e: Exception) {
            Log.e(LogTags.HOME_SCREEN, "💥 加载待审批数据异常: ${e.message}", e)
            approvalData = emptyList()
        } finally {
            isLoadingApproval = false
        }
    }
    
    // 加载待办事项数据
    suspend fun loadTodoData() {
        try {
            Log.d(LogTags.HOME_SCREEN, "开始加载待办事项数据")
            isLoadingTodo = true
            
            val request = JsonObject().apply {
                addProperty("type", 2) // 2.待办
            }
            
            val apiResponse = apiService.getTodoList(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                val todoItems = apiResponse.data.list
                Log.i(LogTags.HOME_SCREEN, "📋 获取到的待办事项数据: ${todoItems.size}条")
                todoData = todoItems.map { todoItem ->
                    Log.d(LogTags.HOME_SCREEN, "📄 待办事项详情:")
                    Log.d(LogTags.HOME_SCREEN, "   🆔 id: ${todoItem.id}")
                    Log.d(LogTags.HOME_SCREEN, "   📝 title: ${todoItem.title}")
                    Log.d(LogTags.HOME_SCREEN, "   📅 created_at: ${todoItem.created_at}")
                    Log.d(LogTags.HOME_SCREEN, "   🔢 form_id: ${todoItem.form_id}")
                    TodoItem(
                        id = todoItem.id.toString(),
                        title = todoItem.title,
                        time = todoItem.created_at,
                        formId = todoItem.form_id
                    )
                }
                Log.i(LogTags.HOME_SCREEN, "✅ 成功加载待办事项数据: ${todoData.size}条")
            } else {
                Log.e(LogTags.HOME_SCREEN, "❌ 加载待办事项数据失败: ${apiResponse.msg}")
                todoData = emptyList()
            }
        } catch (e: Exception) {
            Log.e(LogTags.HOME_SCREEN, "💥 加载待办事项数据异常: ${e.message}", e)
            todoData = emptyList()
        } finally {
            isLoadingTodo = false
        }
    }
    
    // 初始化待审批和待办数据 - 只在首次加载时执行
    LaunchedEffect(Unit) {
        // 如果待审批数据为空，才进行加载
        if (approvalData.isEmpty()) {
            loadApprovalData()
        } else {
            isLoadingApproval = false
        }
        
        // 如果待办数据为空，才进行加载
        if (todoData.isEmpty()) {
            loadTodoData()
        } else {
            isLoadingTodo = false
        }
    }
    
    // 下拉刷新
    val pullRefreshState = rememberPullToRefreshState()
    
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            isRefreshing = true
            // 刷新急需维保电梯数据
            homeRepository.getHomeElevatorList(page = 1, size = 10)
                .onSuccess { data ->
                    homeElevatorList = data.list
                }
                .onFailure { e ->
                    Log.e(LogTags.HOME_SCREEN, "刷新电梯数据失败: ${e.message}")
                }
            // 刷新待审批和待办数据
            loadApprovalData()
            loadTodoData()
            isRefreshing = false
            pullRefreshState.endRefresh()
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(pullRefreshState.nestedScrollConnection)
    ) {
        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            Color(0xFFF8FAFC),
                            Color(0xFFF1F5F9)
                        )
                    )
                ),
            verticalArrangement = Arrangement.spacedBy(20.dp),
            contentPadding = PaddingValues(bottom = AppConstants.TAB_BAR_HEIGHT) // 为TabBar留出空间
        ) {
            item {
                Spacer(modifier = Modifier.height(8.dp))
            }
            
            // 急需维保电梯模块
            item {
                ElevatorMaintenanceSection(
                    title = "急需维保电梯(${displayElevatorData.size})",
                    elevators = displayElevatorData,
                    onViewAll = onNavigateToElevatorList,
                    onElevatorClick = onNavigateToElevatorDetail
                )
            }
            
            // 待审批模块
            item {
                ApprovalSection(
                    title = "待审批(${approvalData.size})",
                    approvals = approvalData,
                    isLoading = isLoadingApproval,
                    onItemClick = onNavigateToApproval
                )
            }
            
            // 待办事项模块
            item {
                TodoSection(
                    title = "待办事项(${todoData.size})",
                    todos = todoData,
                    isLoading = isLoadingTodo,
                    onItemClick = onNavigateToApproval
                )
            }
            
            item {
                Spacer(modifier = Modifier.height(16.dp))
            }
        }
        
        // 下拉刷新容器 - 只在需要时显示
        if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
            PullToRefreshContainer(
                state = pullRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .zIndex(1f) // 确保在列表内容之上
            )
        }
    }
}

@Composable
fun ElevatorMaintenanceSection(
    title: String,
    elevators: List<ElevatorItem>,
    onViewAll: () -> Unit,
    onElevatorClick: (ElevatorItem) -> Unit = {}
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 8.dp,
            pressedElevation = 12.dp
        ),
        shape = RoundedCornerShape(16.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp)
        ) {
            // 标题
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Filled.Warning,
                    contentDescription = null,
                    tint = Color(0xFFEF4444),
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = title,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937)
                )
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            if (elevators.isEmpty()) {
                // 暂无维保电梯
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFFF9FAFB)
                    ),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(24.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = Icons.Filled.CheckCircle,
                            contentDescription = null,
                            modifier = Modifier.size(48.dp),
                            tint = Color(0xFF10B981).copy(alpha = 0.6f)
                        )
                        Spacer(modifier = Modifier.height(12.dp))
                        Text(
                            text = "暂无维保电梯",
                            fontSize = 16.sp,
                            color = Color(0xFF6B7280),
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
            } else {
                // 电梯列表
                elevators.forEach { elevator ->
                    ElevatorItemCard(
                        elevator = elevator,
                        modifier = Modifier
                            .padding(vertical = 6.dp)
                            .clickable { onElevatorClick(elevator) }
                    )
                }
                
                // 查看全部按钮
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp)
                        .clickable { onViewAll() },
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFF3B82F6).copy(alpha = 0.1f)
                    ),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Text(
                        text = "查看全部",
                        fontSize = 16.sp,
                        color = Color(0xFF3B82F6),
                        fontWeight = FontWeight.Medium,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 12.dp),
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}

@Composable
fun ElevatorItemCard(
    elevator: ElevatorItem,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .border(
                width = 2.dp,
                color = if (elevator.isExpired) Color(0xFFEF4444) else Color(0xFF10B981),
                shape = RoundedCornerShape(12.dp)
            ),
        colors = CardDefaults.cardColors(
            containerColor = if (elevator.isExpired) 
                Color(0xFFFEF2F2) 
            else 
                Color(0xFFF0FDF4)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧内容
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Filled.Warning,
                        contentDescription = null,
                        tint = if (elevator.isExpired) Color(0xFFEF4444) else Color(0xFF10B981),
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = elevator.title,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = elevator.description,
                    fontSize = 14.sp,
                    color = if (elevator.isExpired) Color(0xFFDC2626) else Color(0xFF059669),
                    fontWeight = FontWeight.Medium
                )
            }
            
            // 右侧图片（仅当有图片时显示）
            if (elevator.imageUrl != null) {
                Spacer(modifier = Modifier.width(12.dp))
                
                AsyncImage(
                    model = elevator.imageUrl,
                    contentDescription = null,
                    modifier = Modifier
                        .size(70.dp)
                        .clip(RoundedCornerShape(12.dp)),
                    contentScale = ContentScale.Crop
                )
            }
        }
    }
}

@Composable
fun ApprovalSection(
    title: String,
    approvals: List<ApprovalItem>,
    isLoading: Boolean = false,
    onItemClick: (Int) -> Unit = {}
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 8.dp,
            pressedElevation = 12.dp
        ),
        shape = RoundedCornerShape(16.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp)
        ) {
            // 标题
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Filled.Schedule,
                    contentDescription = null,
                    tint = Color(0xFFF59E0B),
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = title,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937)
                )
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            if (isLoading) {
                // 加载状态
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 20.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(24.dp),
                        color = Color(0xFF3B82F6)
                    )
                }
            } else if (approvals.isEmpty()) {
                // 空数据状态
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 20.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无待审批事项",
                        fontSize = 14.sp,
                        color = Color(0xFF6B7280)
                    )
                }
            } else {
                // 数据列表
                approvals.forEach { approval ->
                    ApprovalItemCard(
                        approval = approval,
                        modifier = Modifier.padding(vertical = 6.dp),
                        onClick = onItemClick
                    )
                }
            }
        }
    }
}

@Composable
fun ApprovalItemCard(
    approval: ApprovalItem,
    modifier: Modifier = Modifier,
    onClick: (Int) -> Unit = {}
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { 
                Log.i(LogTags.HOME_SCREEN, "🖱️ 点击待审批项目:")
                Log.i(LogTags.HOME_SCREEN, "   📝 标题: ${approval.title}")
                Log.i(LogTags.HOME_SCREEN, "   🔢 formId: ${approval.formId}")
                onClick(approval.formId) 
            },
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFFFEF3C7)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 图标
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(Color(0xFFF59E0B).copy(alpha = 0.2f)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Filled.Schedule,
                    contentDescription = null,
                    modifier = Modifier.size(20.dp),
                    tint = Color(0xFFF59E0B)
                )
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 标题和时间
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = approval.title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937),
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = approval.time,
                    fontSize = 12.sp,
                    color = Color(0xFF6B7280),
                    fontWeight = FontWeight.Medium
                )
            }
        }
    }
}

@Composable
fun TodoSection(
    title: String,
    todos: List<TodoItem>,
    isLoading: Boolean = false,
    onItemClick: (Int) -> Unit = {}
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 8.dp,
            pressedElevation = 12.dp
        ),
        shape = RoundedCornerShape(16.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp)
        ) {
            // 标题
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Filled.CheckCircle,
                    contentDescription = null,
                    tint = Color(0xFF10B981),
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = title,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937)
                )
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            if (isLoading) {
                // 加载状态
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 20.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(24.dp),
                        color = Color(0xFF3B82F6)
                    )
                }
            } else if (todos.isEmpty()) {
                // 空数据状态
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 20.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无待办事项",
                        fontSize = 14.sp,
                        color = Color(0xFF6B7280)
                    )
                }
            } else {
                // 数据列表
                todos.forEach { todo ->
                    TodoItemCard(
                        todo = todo,
                        modifier = Modifier.padding(vertical = 6.dp),
                        onClick = onItemClick
                    )
                }
            }
        }
    }
}

@Composable
fun TodoItemCard(
    todo: TodoItem,
    modifier: Modifier = Modifier,
    onClick: (Int) -> Unit = {}
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { 
                Log.i(LogTags.HOME_SCREEN, "🖱️ 点击待办事项:")
                Log.i(LogTags.HOME_SCREEN, "   📝 标题: ${todo.title}")
                Log.i(LogTags.HOME_SCREEN, "   🔢 formId: ${todo.formId}")
                onClick(todo.formId) 
            },
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFFECFDF5)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 图标
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(Color(0xFF10B981).copy(alpha = 0.2f)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Filled.CheckCircle,
                    contentDescription = null,
                    modifier = Modifier.size(20.dp),
                    tint = Color(0xFF10B981)
                )
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 标题和时间
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = todo.title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937),
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = todo.time,
                    fontSize = 12.sp,
                    color = Color(0xFF6B7280),
                    fontWeight = FontWeight.Medium
                )
            }
        }
    }
}

/**
 * 判断日期是否过期
 * 将目标日期设置为当天的 23:59:59，与当前时间比较
 */
fun isDateExpired(dateString: String): Boolean {
    return try {
        val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault())
        val targetDate = dateFormat.parse(dateString)
        
        if (targetDate != null) {
            // 将目标日期设置为当天的 23:59:59
            val calendar = java.util.Calendar.getInstance()
            calendar.time = targetDate
            calendar.set(java.util.Calendar.HOUR_OF_DAY, 23)
            calendar.set(java.util.Calendar.MINUTE, 59)
            calendar.set(java.util.Calendar.SECOND, 59)
            calendar.set(java.util.Calendar.MILLISECOND, 999)
            
            val targetDateTime = calendar.time
            val currentDate = java.util.Date()
            
            // 如果当前时间超过了目标日期的 23:59:59，则认为已过期
            currentDate.after(targetDateTime)
        } else {
            false
        }
    } catch (e: Exception) {
        false
    }
}